import {defineConfig, loadEnv} from 'vite';
import vue from '@vitejs/plugin-vue';
import path from 'path';
import Components from 'unplugin-vue-components/vite';
import {AntDesignVueResolver} from 'unplugin-vue-components/resolvers';
import {AntdvLessPlugin, AntdvModifyVars} from 'stepin/lib/style/plugins';

// vite 配置
export default ({command, mode}) => {
    // 获取环境变量
    const env = loadEnv(mode, process.cwd());
    return defineConfig({
        server: {
            proxy: {
                '/api': {
                    // target: env.VITE_API_URL,
                    target: 'http://127.0.0.1:8001/api',
                    ws: true,
                    changeOrigin: true,
                    rewrite: (path) => path.replace(/^\/api/, ''),
                },
            },
            hmr: true,
        },

        resolve: {
            alias: {
                '@': path.resolve(__dirname, 'src'),
            },
        },
        esbuild: {
            jsxFactory: 'h',
            jsxFragment: 'Fragment',
        },
        build: {
            sourcemap: true,
            chunkSizeWarningLimit: 2048,
            // rollupOptions: {
            //   output: {
            //     chunkFileNames: (chunk) => {
            //       return 'assets/' + chunk.name + '.[hash]' + '.' + timestamp + '.js';
            //     },
            //     assetFileNames: (asset) => {
            //       const name = asset.name;
            //       if (name && (name.endsWith('.css') || name.endsWith('.js'))) {
            //         const names = name.split('.');
            //         const extname = names.splice(names.length - 1, 1)[0];
            //         return `assets/${names.join('.')}.[hash].${timestamp}.${extname}`;
            //       }
            //       return 'assets/' + asset.name;
            //     },
            //   },
            // },
        },
        plugins: [
            vue({
                template: {
                    transformAssetUrls: {
                        img: ['src'],
                        'a-avatar': ['src'],
                        'stepin-view': ['logo-src', 'presetThemeList'],
                        'a-card': ['cover'],
                    },
                },
            }),
            Components({
                resolvers: [AntDesignVueResolver({importStyle: mode === 'development' ? false : 'less'})],
            }),
        ],
        css: {
            preprocessorOptions: {
                less: {
                    plugins: [AntdvLessPlugin],
                    modifyVars: AntdvModifyVars,
                    javascriptEnabled: true,
                },
            },
        },
        base: env.VITE_BASE_URL,
    });
};
